package com.yubest.seataaccount.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Map;

@Service
public class AccountService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public Boolean sub(Integer accountId, BigDecimal money) {
        Map<String, Object> map = jdbcTemplate.queryForMap(MessageFormat.format("select * from t_account where id = {0}", accountId));
        if (!map.containsKey("id")) {
            return false;
        }
        BigDecimal wallet = (BigDecimal) map.get("wallet");
        if (wallet.compareTo(money) < 0) {
            return false;
        }
        jdbcTemplate.update(MessageFormat.format("update t_account set wallet = wallet - {0} where id = {1}", money, accountId));
        return true;
    }
}
